package com.gec.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.gec.entity.Order;
import com.gec.entity.OrderItem;
import com.gec.entity.Product;
import com.gec.utils.C3P0Utils;

public class OrderDao {
	QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
	public int addOrder(Order order){
		
		String sql="insert into orders values(?,now(),?,?,?,?,?,?,null)";
		String[] arr={order.getOid(),String.valueOf(order.getTotal()),String.valueOf(order.getState()),
				order.getAddress(),order.getName(),order.getTelephone(),order.getUid()};
		int n=0;
		try {
			n = queryRunner.update(sql,arr);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return n;	
	}
	 public int updateOrderState(String oid) {
	    	QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
	    	String sql = "update orders set state=state+1 where oid=?";
	    	int n = 0;
	    	try {
	    	    n = qr.update(sql, oid);
	    	} catch (SQLException e) {
	    	    // TODO Auto-generated catch block
	    	    e.printStackTrace();
	    	}
	    	return n;
	        }
	 

	 public int deleteOrderItemByOid(String oid) {
			//删除订单记录表中的信息前首先判断他的子表 中的有没有数据
			OrderItemDao orderItemDao = new OrderItemDao();
			//先删除子表中的数据
			List<OrderItem> orderItemByOid = orderItemDao.getOrderItemByOid(oid);
			if(orderItemByOid.size()>0) {
			  orderItemDao.deleteOrderItemByOid(oid);
			}
			
			//再删除主表中的数据
			String sql="delete from orders where oid= ?";
			int n=0;
			try {
				n = queryRunner.update(sql,oid);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return n;
		}

	 
	 public Order getOrderByOid(String oid) {
		  	String sql = "select * from Orders where oid=? order by ordertime desc";
		  	Order order = null;
		  	try {
		  	    order = queryRunner.query(sql, new BeanHandler<Order>(Order.class), oid);
		  	} catch (SQLException e) {
		  	    e.printStackTrace();
		  	}
		  	return order;
		      }
	public List<Order> getOrderListByUid(String uid) {
		String sql = "select * from Orders where uid = ? order by ordertime desc";
		List<Order> list = null;
		try {
		    list = queryRunner.query(sql, new BeanListHandler<>(Order.class),uid);
		} catch (SQLException e) {
		    e.printStackTrace();
		}
		return list;
	}

	




}
